package edu.lnu.project.timeeditapp.activites;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.lnu.project.timeeditapp.R;

import edu.lnu.project.timeeditapp.adapter.MyListViewAdapter;
import edu.lnu.project.timeeditapp.db.TimeEditDataSource;
import edu.lnu.project.timeeditapp.helper.MyHelper;
import edu.lnu.project.timeeditapp.parser.Event;


@SuppressWarnings("deprecation")
public class ListViewActivity extends Activity {

	private MyListViewAdapter mAdapter;
	private Activity mActivity;
	private TimeEditDataSource datasource;
	private int currentWeek;
	private ArrayList<Event> weekEvents;
	private ListView listView;
	public SharedPreferences visibilityColorPreferences;
	public  SharedPreferences.Editor visibilityColorPreferencesEditor;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("OnCreate() portraid");
		
		MyHelper.initializeColors();
		MyHelper.initializeSharedPreferences(this);
		MyHelper.initializeArray(this);
		startService();
		
		//Check orientation and start correct activity according to that
		checkForCorrectOrientation();
		mActivity = this;
		initializeSharedPreferences(mActivity);
		setContentView(R.layout.listview_activity);
		listView = (ListView)findViewById(R.id.listView1);


		datasource = new TimeEditDataSource(this);
		MyHelper.currentWeek = MyHelper.getCurrentWeek();
		currentWeek = MyHelper.currentWeek;

		//Create adapter
		mAdapter = new MyListViewAdapter((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE), mActivity);

		//Add all events to the adapter
		datasource.open();
		weekEvents = datasource.getWeekEvents( currentWeek );
		datasource.close();
		addEventsToAdapter( weekEvents );

		//Set adapter
		listView.setAdapter(mAdapter); 

		//Create buttons
		setUpButtons();

		//Set up the action bar
		ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);


	}
	
	public void startService(){
		Intent intent = new Intent(this.getApplicationContext(), ReminderService.class );
		this.startService(intent);
	}

	public void initializeSharedPreferences(Context mContext){
		visibilityColorPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		visibilityColorPreferencesEditor = visibilityColorPreferences.edit();
	}

	@Override
	protected void onResume() {
		//Check orientation and start correct activity
		checkForCorrectOrientation();
		System.out.println("OnResume() Portraid");
		super.onResume();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) { // TODO Call new activity
		super.onConfigurationChanged(newConfig);

		System.out.println("onConfigurationChanged() listten gelen");

		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
			MyHelper.currentWeek = currentWeek;
			System.out.println("(list) rotation: "+currentWeek);
			/* Start new Activity DebugActivity */
			Intent intent = new Intent(this, GridViewActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			this.startActivity(intent);

		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
			System.out.println("current week after (list) rotation: "+currentWeek);
			if(currentWeek != MyHelper.currentWeek){
				currentWeek = MyHelper.currentWeek;
				datasource.open();
				addEventsToAdapter( datasource.getWeekEvents( currentWeek ) );
				datasource.close();
			}
			Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
		} else {
			//WILL NEVER HAPPEN
		}
	}

	/**
	 * Check orientation and destroy activity its the wrong one
	 */
	private void checkForCorrectOrientation(){
		// Check so the orientation is correct for this activity
		if( getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT ){
			//Destroy activity
			finish();
		}
		else{
		}
	}


	/**
	 * Adds the events to the adapter
	 * @param ArrayList<Event>
	 */
	private void addEventsToAdapter(ArrayList<Event> events){

		//Remove all previous events from list
		mAdapter.clear();

		Boolean isFirstDay = true;
		int countEvents = 0;
		String previousDay = "";

		// Check so there are some events
		if(events.size() != 0){

			//While there still are events in the list
			while(countEvents < events.size()){

				// First we always print the day
				if(isFirstDay){	

					// Get the day
					previousDay = events.get(0).getBeginDate();

					// Use first event to be able to find right day
					mAdapter.addDayItem(events.get(0)); 

					//No more events can be firstDay
					isFirstDay = false;
				} 
				// Check so its not a new day
				else if( events.get(countEvents).getBeginDate().contains(previousDay) ){ 
					//Add event item
					mAdapter.addEventItem(events.get(countEvents));

					//Go to next event
					countEvents++;
				}
				// When its a new day add a new day seperator
				else{
					//Add new day item
					mAdapter.addDayItem(events.get(countEvents));

					//Set previous day to this day
					previousDay = events.get(countEvents).getBeginDate();
				}
			}

		}
		else{
			Toast.makeText(this, "Week doesn't contain any events", Toast.LENGTH_LONG).show();
		}

		//Set week
		TextView tvWeek = (TextView)findViewById(R.id.textViewListViewWeek);
		tvWeek.setText("Week "+currentWeek);
	}
	
	
	/**
	 * Create all the buttons
	 */
	private void setUpButtons(){
		ImageButton buttonNextWeek = (ImageButton)findViewById(R.id.buttonListViewNextWeek);
		buttonNextWeek.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				datasource.open();
				currentWeek = MyHelper.changeWeek(currentWeek, 1);
				addEventsToAdapter( datasource.getWeekEvents( currentWeek ) );
				datasource.close();

			}

		});

		ImageButton buttonPreviousWeek = (ImageButton)findViewById(R.id.buttonListViewPreviousWeek);
		buttonPreviousWeek.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				datasource.open();
				currentWeek = MyHelper.changeWeek(currentWeek, -1) ;
				addEventsToAdapter( datasource.getWeekEvents( currentWeek ) );
				datasource.close();

			}

		});

		Button buttonCurrentWeek = (Button)findViewById(R.id.buttonListViewCurrentWeek);
		buttonCurrentWeek.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				datasource.open();
				currentWeek = MyHelper.getCurrentWeek();
				addEventsToAdapter( datasource.getWeekEvents( currentWeek ) );
				datasource.close();	
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.action_menu_listview, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { 

		switch (item.getItemId()) {
		case R.id.actionMenuListViewSettings:  	
			/* Start new Activity SetPrefrencesTimeedit */
			Intent visibilityColorScreenIntent = new Intent(mActivity, VisibilityColorScreen.class);
			visibilityColorScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(visibilityColorScreenIntent, 1);
			return true;
		case R.id.actionMenuListViewRefreshSelectfile:  	
			/* Start new Activity SelectFileActivity */
			Intent refreshIntent = new Intent(mActivity, SelectFileActivity.class);
			mActivity.startActivity(refreshIntent);
			mActivity.finish();
			return true;
		case R.id.actionMenuListViewSilent:
			/* Start new silentMode switch dialog */
			LayoutInflater inflater = LayoutInflater.from(this);
			View mView = inflater.inflate(R.layout.silent_mode_dialog, null);

			final LinearLayout silentModeMainLayout = (LinearLayout) mView.findViewById(R.id.silentModeMainLayout);
			final TextView silentExplaination = (TextView) mView.findViewById(R.id.silentExplaination);
			final ToggleButton silentToggle = (ToggleButton) mView.findViewById(R.id.silentMode);
			final TextView star1 = (TextView) mView.findViewById(R.id.star1);
			final TextView star2 = (TextView) mView.findViewById(R.id.star2);
			final TextView moon = (TextView) mView.findViewById(R.id.moon);
			

			final Resources res = mActivity.getResources();
			if(visibilityColorPreferences.getBoolean(MyHelper.SILENTMODE, false)){
				star1.setVisibility(View.VISIBLE);
				star2.setVisibility(View.VISIBLE);
				moon.setVisibility(View.VISIBLE);
				silentModeMainLayout.setBackgroundDrawable(res.getDrawable(R.drawable.silent_mode_background));
				silentExplaination.setText(res.getString(R.string.silentModeOn));
				silentExplaination.setTextColor(res.getColor(R.color.LnuYellow));
				silentToggle.setChecked(true);
				
			}
			else{
				star1.setVisibility(View.GONE);
				star2.setVisibility(View.GONE);
				moon.setVisibility(View.GONE);
				silentModeMainLayout.setBackgroundDrawable(res.getDrawable(R.drawable.silent_mode_off_background));
				silentExplaination.setText(res.getString(R.string.silentModeOff));
				silentExplaination.setTextColor(Color.BLACK);
				silentToggle.setChecked(false);
			}
			
			silentToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(isChecked){
						visibilityColorPreferencesEditor.putBoolean(MyHelper.SILENTMODE, true).commit();
						star1.setVisibility(View.VISIBLE);
						star2.setVisibility(View.VISIBLE);
						moon.setVisibility(View.VISIBLE);
						silentModeMainLayout.setBackgroundDrawable(res.getDrawable(R.drawable.silent_mode_background));
						silentExplaination.setText(res.getString(R.string.silentModeOn));
						silentExplaination.setTextColor(res.getColor(R.color.LnuYellow));
						
					}
					else {
						visibilityColorPreferencesEditor.putBoolean(MyHelper.SILENTMODE, false).commit();
						star1.setVisibility(View.GONE);
						star2.setVisibility(View.GONE);
						moon.setVisibility(View.GONE);
						silentModeMainLayout.setBackgroundDrawable(res.getDrawable(R.drawable.silent_mode_off_background));
						silentExplaination.setText(res.getString(R.string.silentModeOff));
						silentExplaination.setTextColor(Color.BLACK);
						
					}
					
					
				}
			});
			new AlertDialog.Builder(mActivity).setView(mView).setNeutralButton(android.R.string.ok, null).show();
			return true;
		default:
			finish();
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode,int resultCode, Intent result) {

		//Add the new item as country_item from the activity to the adapter
		if (resultCode == RESULT_OK) {
			addEventsToAdapter(weekEvents);
			mAdapter.notifyDataSetChanged();
		}
		else if(true){

		}
	}
}